﻿Imports System.IO
Imports System.Net.Mail
Imports myBookmarks.Core
Namespace myBookmarks.Infrastructure
    Public Class EmailSender
        Implements IEmailSender
        Private _settings As IConfigurationSettings
        Public Sub New(ByVal settings As IConfigurationSettings)
            _settings = settings
        End Sub
        Public Sub SendPasswordResetEmail(ByVal email As String, ByVal username As String, ByVal reseturl As String) Implements IEmailSender.SendPasswordResetEmail
            Dim body As String = ReadFromFile("ResetPassword")
            body = String.Format(body, username, reseturl, _settings.RootUrl, _settings.SiteTitle)
            Dim subject As String = String.Format("Your password request from {0} ", _settings.SiteTitle)
            SendEmail(email, _settings.EmailFromAddress, subject, body)
        End Sub
        Public Sub SendBookmarkEmail(ByVal email As String, ByVal username As String, ByVal bookmark As Bookmark, ByVal subject As String, ByVal message As String) Implements IEmailSender.SendBookmarkEmail
            Dim body As String = message & "<br/> I have shared a link with you.<br/>"
            body = body & String.Format("<a href=""{0}"">{1}</a>", bookmark.Location, bookmark.Name)
            SendEmail(email, username, subject, body)
        End Sub
        Function ReadFromFile(ByVal templateName As String)
            Dim templatedirectory As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _settings.EmailTemplateDirectory)
            Dim filepath As String = String.Concat(Path.Combine(templatedirectory, templateName), ".txt")
            Return File.ReadAllText((filepath))
        End Function
        Sub SendEmail(ByVal emailTo As String, ByVal emailfrom As String, ByVal subject As String, ByVal body As String)
            Dim message As New MailMessage(emailfrom, emailTo, subject, body)
            message.From = New MailAddress(emailfrom, emailfrom)
            message.ReplyTo = New MailAddress(emailfrom)
            message.IsBodyHtml = True
            message.Sender = New MailAddress(emailfrom)
            Threading.ThreadPool.QueueUserWorkItem(AddressOf SendEmail, message)
        End Sub
        Sub SendEmail(ByVal msg As Object)
            Try
                Dim _message As MailMessage = DirectCast(msg, MailMessage)
                Dim smtp As New SmtpClient()
                smtp.EnableSsl = _settings.EmailEnableSSL
                smtp.Send(msg)
            Catch e As Exception
                Throw e
            End Try
        End Sub
    End Class


End Namespace